import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import com.sun.sgs.client.ClientChannel;
import com.sun.sgs.client.simple.SimpleClient;

/**
 * This class should be the controller that will handle the SimpleClients that must be connected to SGS-Server (DarkStar Server). 
 * @author fabiosl
 *
 */
public class PlayerController {
	private static Map<Player, SimpleClient> playersMap = new HashMap<Player, SimpleClient>();
	private static Map<String, ClientChannel> channelMap = new HashMap<String, ClientChannel>();
	private List<Room> availableRooms = new ArrayList<Room>();
	private AgentProcessor agentProcessor =   new AgentProcessor();

	public static Map<String, ClientChannel> getChannelMap(){
		return channelMap;
	}
	public static void main(String[] args) throws InterruptedException {
		PlayerController handler = new PlayerController();
		handler.login("fabio2", "sousaleal.fabio");
		Thread.sleep(5000);
		System.out.println("Number of Logged players: "
				+ handler.playersMap.size());
//		handler.login("fabio", "654321");
//		Thread.sleep(5000);
//		System.out.println("Number of Logged players: "
//				+ handler.playersMap.size());
	}

	public void login(String username, String password) {
		try {
			JSONObject jsonObj = new JSONObject();
			jsonObj.append("cmd","LOGIN");
			jsonObj.append("username", username);
			jsonObj.append("password", password);
			jsonObj.append("scene", "ALL_SCENE");
			this.agentProcessor.processCommand(jsonObj);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public List<Room> getAvailableRooms() {
		return availableRooms;
	}

	public void setAvailableRooms(List<Room> availableRooms) {
		this.availableRooms = availableRooms;
	}

	public static Map<Player, SimpleClient> getPlayersMap() {
		return playersMap;
	}

	public static SimpleClient getOrCreatePlayerClient(String userId) {
		Player p = new Player(userId, "");
		return getOrCreatePlayerClient(p);
	}
	
	public static SimpleClient getOrCreatePlayerClient(Player player) {
		 Map<Player, SimpleClient> map = playersMap; 
		if (!playersMap.isEmpty()) {
			for (Player p : playersMap.keySet()) {
				if (player.getUserId() == p.getUserId())
					return playersMap.get(p);
			}
		}
		SimpleClient client = new SimpleClient(new ClientListener(player.getUserId(), player.getPassword()));
		playersMap.put(player, client);
		return client;
	}

}
